<script setup>
import {onMounted, reactive, ref} from 'vue'
import {
  ElButton,
  ElInput,
  ElMessage,
  ElMessageBox,
  ElOption,
  ElPagination,
  ElSelect,
  ElTable,
  ElTableColumn,
  ElTag
} from 'element-plus'
import http from "@/request/Http.js";
import {useRouter} from "vue-router";

const router = useRouter();

// 表格数据
const tableData = ref([]);
const total = ref(0);
const loading = ref(false);

// 查询参数
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  productName: '',
  status: '' // 空字符串表示未选择
});

// 状态选项映射
const statusOptions = [
  {label: '全部', value: ''},
  {label: '下架', value: 0},
  {label: '已上架', value: 1},
  {label: '审核中', value: 2},
  {label: '已售出', value: 3},
  {label: '已预定', value: 4},
  {label: '审核不通过', value: 5},
];

// 状态显示配置
const statusConfig = {
  0: {label: '下架', type: 'info'},
  1: {label: '已上架', type: 'success'},
  2: {label: '审核中', type: 'warning'},
  3: {label: '已售出', type: 'primary'},
  4: {label: '已预定', type: 'purple'},
  5: {label: '审核不通过', type: 'danger'}
};

// 获取我的商品列表
const getMyGoods = async () => {
  loading.value = true;
  try {
    const params = {
      currentPage: queryParams.page,
      pageSize: queryParams.pageSize,
      productName: queryParams.productName,
      status: queryParams.status === '' ? null : queryParams.status // 空字符串转 null
    };
    console.log('状态搜索参数:', params.status); // 调试用：确认状态参数是否正确

    const response = await http.get('/product/myGoods', {params});

    if (response.code === 200) {
      tableData.value = response.data.records;
      total.value = response.data.total;
    } else {
      ElMessage.error(response.msg || '获取商品列表失败');
    }
  } catch (error) {
    console.error('获取商品列表失败:', error);
    ElMessage.error('网络错误，获取商品列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  queryParams.page = 1; // 重置为第一页
  getMyGoods();
};

// 重置搜索
const resetSearch = () => {
  queryParams.productName = '';
  queryParams.status = '';
  queryParams.page = 1;
  getMyGoods();
};

// 分页变更
const handlePageChange = (page) => {
  queryParams.page = page;
  getMyGoods();
};

// 分页大小变更
const handlePageSizeChange = (pageSize) => {
  queryParams.pageSize = pageSize;
  queryParams.page = 1;
  getMyGoods();
};

// 编辑商品
const handleEdit = (id) => {
  router.push({path: '/userHome/addGood', query: {id: id}});
};

// 查看商品详情
const handleViewDetail = (id) => {
  router.push(`/userHome/showGood/${id}`);
};

// 删除商品
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该商品吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await http.delete(`/product/deleteGood/${id}`);
    if (response.code === 200) {
      ElMessage.success('删除成功');
      await getMyGoods();
    } else {
      ElMessage.error(response.msg || '删除失败');
    }
  } catch (error) {
    if (error.name !== 'Error') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

// 发布新商品
const goToPublish = () => {
  router.push('/userHome/addGood');
};

// 页面加载时获取数据
onMounted(() => {
  getMyGoods();
});
</script>

<template>
  <div class="my-goods-container">
    <div class="page-header">
      <h2>我的商品</h2>
      <el-button type="primary" @click="goToPublish">
        发布商品
      </el-button>
    </div>

    <div class="search-bar">
      <el-input
          v-model="queryParams.productName"
          clearable
          placeholder="请输入商品名称"
          style="width: 300px; margin-right: 10px;"
      ></el-input>

      <el-select
          v-model="queryParams.status"
          clearable
          placeholder="请选择状态"
          style="width: 180px; margin-right: 10px;"
          @change="handleSearch"
      >
        <el-option
            v-for="item in statusOptions"
            :key="item.value + item.label"
            :label="item.label"
            :value="item.value"
        ></el-option>
      </el-select>

      <el-button type="primary" @click="handleSearch">
        搜索
      </el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>

    <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%; margin-top: 20px;"
    >
      <el-table-column label="商品图片" sort-order="asc" sortable="custom" width="120">
        <template #default="scope">
          <img
              :alt="scope.row.name"
              :src="scope.row.images?.[0]?.imageUrl || 'https://picsum.photos/100/100'"
              class="goods-image"
              @error="e => e.target.src = 'https://picsum.photos/100/100'"
          >
        </template>
      </el-table-column>
      <el-table-column label="商品名称" prop="name" width="200"></el-table-column>
      <el-table-column label="价格" prop="price" width="100">
        <template #default="scope">¥{{ scope.row.price.toFixed(2) }}</template>
      </el-table-column>
      <el-table-column label="分类" prop="categoryName" width="120"></el-table-column>
      <el-table-column label="状态" prop="status" width="120">
        <template #default="scope">
          <el-tag :type="statusConfig[scope.row.status]?.type || 'default'">
            {{ statusConfig[scope.row.status]?.label || '未知状态' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="浏览量" prop="viewCount" width="100"></el-table-column>
      <el-table-column label="发布时间" prop="createdAt" width="160"></el-table-column>
      <el-table-column label="操作" width="260">
        <template #default="scope">
          <el-button
              size="small"
              type="info"
              @click="handleViewDetail(scope.row.id)"
          >
            查看详情
          </el-button>
          <el-button
              size="small"
              type="primary"
              @click="handleEdit(scope.row.id)"
          >
            修改
          </el-button>
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
      <template #empty>
        <div style="padding: 40px 0; text-align: center;">
          <p>暂无商品数据</p>
          <el-button type="text" @click="goToPublish">去发布商品</el-button>
        </div>
      </template>
    </el-table>

    <div v-if="total > 0" class="pagination">
      <el-pagination
          :current-page="queryParams.page"
          :page-size="queryParams.pageSize"
          :page-sizes="[5, 10, 20]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageSizeChange"
          @current-change="handlePageChange"
      ></el-pagination>
    </div>
  </div>
</template>

<style scoped>
.my-goods-container {
  padding: 24px;
  max-width: 1400px;
  margin: 0 auto;
  background-color: #f9fafb;
  min-height: calc(100vh - 48px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.page-header h2 {
  font-size: 22px;
  font-weight: 600;
  color: #1d2129;
  margin: 0;
}

.search-bar {
  background-color: #ffffff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  border: none;
}

:deep(.el-table th) {
  background-color: #f7f8fa;
  font-weight: 500;
  color: #4e5969;
  padding: 14px 0;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-table tr) {
  transition: background-color 0.2s ease;
}

:deep(.el-table tr:hover > td) {
  background-color: #f7f8fa !important;
}

:deep(.el-table td) {
  padding: 16px 0;
  border-bottom: 1px solid #f5f5f5;
}

/* 表格空状态样式 */
:deep(.el-table__empty-block) {
  padding: 60px 0 !important;
}

:deep(.el-table__empty-text) {
  font-size: 14px;
  color: #86909c;
  margin-bottom: 16px;
}

/* 按钮样式优化 */
:deep(.el-button) {
  border-radius: 4px;
  transition: all 0.2s ease;
}

:deep(.el-button--primary) {
  background-color: #4096ff;
  border-color: #4096ff;
}

:deep(.el-button--primary:hover) {
  background-color: #69b1ff;
  border-color: #69b1ff;
}

:deep(.el-button--info) {
  background-color: #0fc6c2;
  border-color: #0fc6c2;
}

:deep(.el-button--info:hover) {
  background-color: #36daca;
  border-color: #36daca;
}

:deep(.el-button--danger) {
  background-color: #ff4d4f;
  border-color: #ff4d4f;
}

:deep(.el-button--danger:hover) {
  background-color: #ff7875;
  border-color: #ff7875;
}

/* 输入框和选择器样式 */
:deep(.el-input__inner), :deep(.el-select__inner) {
  border-radius: 4px;
  border-color: #dcdfe6;
  transition: all 0.2s ease;
  height: 36px;
}

:deep(.el-input__inner:focus), :deep(.el-select__inner:focus) {
  border-color: #4096ff;
  box-shadow: 0 0 0 2px rgba(64, 150, 255, 0.2);
}

/* 标签样式优化 */
:deep(.el-tag) {
  border-radius: 4px;
  padding: 3px 8px;
  font-size: 12px;
}

:deep(.el-tag--purple) {
  background-color: #722ed1;
  border-color: #722ed1;
}

/* 分页样式 */
.pagination {
  margin-top: 24px;
  text-align: right;
  padding: 16px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

:deep(.el-pagination) {
  font-size: 14px;
}

:deep(.el-pagination__item) {
  border-radius: 4px;
  margin: 0 3px;
  width: 32px;
  height: 32px;
  line-height: 32px;
}

:deep(.el-pagination__item.active) {
  background-color: #4096ff;
  border-color: #4096ff;
}

/* 商品图片样式 */
.goods-image {
  width: 90px;
  height: 70px;
  object-fit: contain;
  border-radius: 4px;
  padding: 4px;
  background-color: #f9f9f9;
  transition: transform 0.2s ease;
}

.goods-image:hover {
  transform: scale(1.05);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .my-goods-container {
    padding: 16px;
  }

  .search-bar {
    padding: 16px;
  }

  .page-header h2 {
    font-size: 18px;
  }
}
</style>
